package com.factory.rest.config;

import com.factory.common.constant.ResultCode;
import com.factory.common.constant.UserConstant;
import com.factory.common.core.LoginException;
import com.factory.common.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器
 * 判断用户是否登录
 */
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader(UserConstant.USERTOKEN);

        if (StringUtil.isEmpty(token)) {
            log.warn("no token request uri,{}",request.getRequestURI());
            throw new LoginException(ResultCode.NoLogin.code, ResultCode.NoLogin.message);
        }

        Object attribute = request.getSession().getAttribute(UserConstant.getToken(token));
        if (null == attribute) {
            log.warn("no login info request uri,{}",request.getRequestURI());
            throw new LoginException(ResultCode.LoginExpired.code, ResultCode.LoginExpired.message);
        }

        return true;
    }

}
